import ProductService from '../../services/product'
import { Utils } from '../../utils/utils'
import { noConsole } from '../../config';
import ProductUtils from '../../utils/product'

const productService = new ProductService()
const productUtils = new ProductUtils()

/**
 * 根据产品对象初始化表单数据
 */
function initFrom (product: any): any {
  const form = {}
  form['deposit'] = product.min_deposit
  form['time_limit'] = product.min_time_limit
  return form
}

export default {
  namespace: 'bankProductDetial',
  state: {
   product: {},   // 产品
   allTimeLimitOptions: [],  // 产品贷款期限数组
   form: {         // 表单
     deposit: 0,
     time_limit: 0,
   },
   redirectToUrl: '/pages/bankProductApply/index',  // 要跳转页面的url
  },
  effects: {
    // 查询银行产品详情
    * getBankProductDetail({ payload }, {call, put, select}) {
      
      const { redirectToUrl } = yield select(state => state.bankProductDetial)
      const { code, data } = yield call(productService.getBankDetail.bind(productService),  payload.product_id )
      if (code === 0) {
        
        // 计算产品的贷款期限数组
        const allTimeLimitOptions = productUtils.getTimeLimitOptions(data)

        // 初始化表单
        const form = initFrom(data)

        // 更新产品详情对象
        yield put({
          type: 'save', 
          payload: {
            product: data,
            allTimeLimitOptions,
            form,
          } 
        });
      }
    },
  },
  reducers: {
    // 更新state
    save(state, { payload }) {
      return {...state, ...payload};
    },
    // 更新表单
    updateForm(state, { payload }) {
      const { form } = state
      const newForm = payload
      
      const formCopy = Object.assign({}, form, newForm)
      return {...state, form: formCopy }
    }
  },
};
